<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="订单状态"
          clearable
          size="small"
          style="width: 110px"
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.code"
            :label="dict.msg"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分销商" prop="traderAccount">
        <el-select
          v-model="queryParams.traderAccount"
          placeholder="分销商"
          clearable
          size="small"
          style="width: 150px"
          @change="accountSelect"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.trader"
            :label="dict.traderName"
            :value="dict.trader"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发车日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="-" prop="endDate" label-width="10">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发车时间" prop="startTime">
        <el-time-select
          style="width: 110px"
          placeholder="请选择"
          v-model="queryParams.startTime"
          :picker-options="{
            start: '00:00',
            step: '01:00',
            end: '23:00',
          }"
        >
        </el-time-select>
      </el-form-item>
      <el-form-item label="-" prop="endTime" label-width="10">
        <el-time-select
          style="width: 110px"
          placeholder="请选择"
          v-model="queryParams.endTime"
          :picker-options="{
            start: '00:00',
            step: '01:00',
            end: '23:00',
            minTime: queryParams.startTime,
          }"
        >
        </el-time-select>
      </el-form-item>
      <!-- 新增 -->
      <el-form-item label="预定日期" prop="preStartDate">
        <el-date-picker
          v-model="queryParams.preStartDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="-" prop="preEndDate" label-width="10">
        <el-date-picker
          v-model="queryParams.preEndDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出发地" prop="stationCode">
        <el-autocomplete
          class="inline-input"
          clearable
          v-model="selectStationName"
          :fetch-suggestions="StationQuerySearch"
          placeholder="请输入内容"
          style="width: 160px"
          :trigger-on-focus="false"
          @select="getStationCode"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="目的地" prop="targetName">
        <el-input
          v-model="queryParams.targetName"
          placeholder="请输入目的地"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 新增结束 -->
      <el-form-item label="订单号" prop="keyword">
        <el-autocomplete
          style="width: 280px"
          class="inline-input"
          clearable
          v-model="queryParams.keyword"
          :fetch-suggestions="querySearch"
          placeholder="请输入订单号、手机号、班次搜索"
          @select="handleSelect"
          @keyup.enter.native="handleQuery"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          v-hasPermi="['service:orderList:query']"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button
          icon="el-icon-refresh"
          size="mini"
          v-hasPermi="['service:orderList:query']"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 退手续费/服务费模态框 -->
    <el-dialog
      title="申请退手续费"
      :visible.sync="RefDialogFormVisible"
      width="550px"
    >
      <div id="refDiv">
        <el-row :gutter="20">
          <el-col class="refItem" :span="8" :offset="0">
            服务费: {{ refundInfo.serviceFee }}元</el-col
          >
          <el-col class="refItem" :span="8" :offset="0">
            手续费: {{ refundInfo.refundFee }}元</el-col
          >
          <el-col class="refItem" :span="24" :offset="0">
            退款:
            <el-radio-group
              v-model="feeData.refundType"
              @change="radioRefMoney"
            >
              <el-radio :label="1">全部退款</el-radio>
              <el-radio :label="2">退手续费</el-radio>
              <el-radio :label="3">退服务费</el-radio>
            </el-radio-group>
          </el-col>
          <el-col class="refItem" :span="24" :offset="0">
            退款金额:
            <span style="color: #ff7b48"
              >{{ feeData.refundFee }}元</span
            ></el-col
          >
          <el-col class="refItem" :span="24" :offset="0">
            退款原因:
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入内容"
              v-model="feeData.refundReason"
            >
            </el-input
          ></el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="RefDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="feeSend">确 定</el-button>
      </div>
    </el-dialog>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:logininfor:export']"
          >导出</el-button
        >
      </el-col> -->
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center"/> -->
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="分销商" align="center" prop="traderAccount" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <span>{{ getStatus(scope.row.orderStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班次" align="center" prop="busNum" />
      <el-table-column label="出发地" align="center" prop="stationName" />
      <el-table-column label="目的地" align="center" prop="targetName" />
      <el-table-column label="发车时间" align="center" prop="startDateTime" />
      <el-table-column label="在线退票" align="center" prop="isSupportRefund">
        <template slot-scope="scope">
          <span>{{ scope.row.isSupportRefund ? "支持" : "不支持" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户手机号" align="center" prop="userPhone" />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="orderPassword">
            <el-button v-hasPermi="['service:orderList:edit']" plain>
              <span class="el-dropdown-link">
                下拉菜单<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="[1, scope]">详情</el-dropdown-item>
              <el-dropdown-item :command="[2, scope]"
                >取票密码</el-dropdown-item
              >
              <el-dropdown-item :command="[3, scope]"
                >清除购票记录</el-dropdown-item
              >

              <el-dropdown-item
                :disabled="scope.row.isRefund"
                :command="[4, scope]"
                >{{
                  scope.row.isRefund == true ? "已申请退款" : "申请退款"
                }}</el-dropdown-item
              >

              <el-dropdown-item
                :disabled="!scope.row.isCanRefundFee"
                :command="[5, scope]"
                >退手续费</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修退款对话框 -->
    <el-dialog
      title="修改退款申请"
      :visible.sync="open"
      width="550px"
      append-to-body
    >
      <order-ref v-on:success="success" :parentRefData="message"></order-ref>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
// import { list, delLogininfor, cleanLogininfor } from "@/api/system/logininfor";
import { querystations } from "@/api/order/refundList";
import {
  list,
  querytrader,
  queryorderpwd,
  cleanprehistory,
  queryorderdetail,
  applyrefund,
  applyrefundfee,
} from "@/api/service/orderList";
import orderRef from "../module/orderListRef";
import utils from "../../js/index";
export default {
  name: "OrderList",
  components: {
    orderRef,
  },
  data() {
    return {
      statusList: [
        { msg: "全部", code: 100 },
        { msg: "待支付", code: 0 },
        { msg: "已支付", code: 1 },
        { msg: "已取消", code: 2 },
        { msg: "已打印", code: 3 },
        { msg: "申请退款", code: 6 },
        { msg: "退款成功", code: 7 },
        { msg: "用户申请退款", code: 8 },
        { msg: "用户申请退款成功", code: 9 },
      ],
      radio: "true",
      // 退款/修改退款模态框
      open: false,
      // dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      // 退款所需数据
      refdata: {
        orderCode: "",
        isRefundServiceFee: true,
        refundFeeRate: undefined,
        refundMoeny: "",
        refundReason: "",
        des: "",
        shouPay: "",
      },
      // 退款手续费
      refMsg: [
        {
          value: 0,
          label: "不收取手续费",
        },
        {
          value: 10,
          label: "收取10%手续费",
        },
        {
          value: 20,
          label: "收取20%手续费",
        },
        {
          value: 50,
          label: "收取50%手续费",
        },
      ],
      options: [
        {
          value: "超时",
          label: "超时",
        },
        {
          value: "车站停班",
          label: "车站停班",
        },
        {
          value: "车站下班",
          label: "车站下班",
        },
        {
          value: "车站断网",
          label: "车站断网",
        },
        {
          value: "车站停电",
          label: "车站停电",
        },
        {
          value: "车站班次信息有误（提前发车等）",
          label: "车站班次信息有误（提前发车等）",
        },
        {
          value: "车站同意退款",
          label: "车站同意退款",
        },
        {
          value: "推送信息有误",
          label: "推送信息有误",
        },

        {
          value: "已打印（未出票、车站同意退款）",
          label: "已打印（未出票、车站同意退款）",
        },
        {
          value: "自助机购票失败",
          label: "自助机购票失败",
        },
        {
          value: "自助机故障",
          label: "自助机故障",
        },

        {
          value: "车站支持在线退票（扣除...手续费）",
          label: "车站支持在线退票（扣除...手续费）",
        },
        {
          value: "乘客原因（此项一定要写清楚原因）",
          label: "乘客原因（此项一定要写清楚原因）",
        },
        {
          value: "其他",
          label: "其他",
        },
      ],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: 100,
        traderAccount: "all",
        keyword: "",
        startDate: "",
        endDate: "",
        startTime: "",
      endTime: "",
      },
      parentRefData: {},
      refundInfo: {},
      // 申请退手续费弹框
      RefDialogFormVisible: false,
      // 退手续费所需数据
      feeData: {
        orderCode: undefined,
        refundType: undefined,
        refundServiceFee: undefined,
        refundFee: 0,
        refundReason: undefined,
      },
      arr: [],
      message: {},
      selectStationName: "",
    };
  },
  created() {
    this.getDicts();
    this.getSearchList();
    this.getStationList();
  },
  methods: {
    StationQuerySearch(queryString, cb) {
      var restaurantsStation = this.stationList;
      var results = queryString
        ? restaurantsStation.filter(this.StationCreateFilter(queryString))
        : restaurantsStation;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    StationCreateFilter(queryString) {
      return (v) => {
        return v.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    getStationList() {
      querystations().then((res) => {
        if (res.code == 200) {
          var arr = res.data.map((e) => {
            return { value: e.stationName, name: e.globalCode };
          });
          this.stationList = arr;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    getStationCode(v) {
      this.queryParams.stationCode = v.name;
    },
    accountSelect(v) {
      if (!v) {
        this.queryParams.traderAccount = "all";
      }
    },
    getStatus(val) {
      return utils.utils.getStatus(val);
    },
    orderPassword(data) {
      switch (data[0]) {
        case 1:
          // 跳转到详情页面
          let routeData = this.$router.resolve({
            path: `orderMessage`,
            query: {
              orderCode: data[1].row.orderCode,
            },
          });
          window.open(routeData.href, "_blank");
          break;
        case 2:
          // 获取取票密码
          queryorderpwd({ orderCode: data[1].row.orderCode }).then((res) => {
            if (res.code == 200) {
              this.$alert(
                `<div><p style="width:40%;display: inline-block;">座位号: ${res.data.seatNums}</p><p style="width:40%;display: inline-block;">张数: ${res.data.ticketAmount}</p><p>取票密码: ${res.data.pwd}</p></div>`,
                "取票密码",
                {
                  dangerouslyUseHTMLString: true,
                }
              );
            } else {
              this.$message.error(res.msg);
            }
          });
          break;
        case 3:
          // 清除购票记录
          this.$confirm("点击确定清除购票记录", "清除购票记录", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            cleanprehistory({ orderCode: data[1].row.orderCode }).then(
              (res) => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                } else {
                  this.$message.error(res.msg);
                }
              }
            );
          });
          break;
        case 4:
          // 退款
          this.orderMessage(data[1].row.orderCode, true);
          this.refdata.orderCode = data[1].row.orderCode;
          // this.dialogFormVisible = true;
          break;
        case 5:
          this.orderMessage(data[1].row.orderCode);
          this.feeData.orderCode = data[1].row.orderCode;
          this.RefDialogFormVisible = true;
          break;
        default:
          break;
      }
    },
    // 退款子组件模态框
    success(type, viewData) {
      viewData.refundFeeRate = viewData.refundFeeRate
        ? viewData.refundFeeRate
        : 0;
      const that = this;
      if (type == 1) {
        that.open = false;
      } else {
        applyrefund(viewData)
          .then((res) => {
            if (res.code == 200) {
              that.open = false;
              that.getList();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {});
      }
    },
    feeSend() {
      applyrefundfee(this.feeData)
        .then((res) => {
          if (res.code == 200) {
            this.RefDialogFormVisible = false;
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          // this.$message.error(err);
        });
    },

    radioRefMoney(val) {
      switch (val) {
        case 1:
          this.feeData.refundFee =
            Number(this.refundInfo.serviceFee) +
            Number(this.refundInfo.refundFee);
          break;
        case 2:
          this.feeData.refundFee = Number(this.refundInfo.refundFee);
          break;
        case 3:
          this.feeData.refundFee = Number(this.refundInfo.serviceFee);
          break;

        default:
          break;
      }
    },
    // 查询订单详情：退票
    orderMessage(code, refOrder) {
      queryorderdetail({ orderCode: code })
        .then((res) => {
          if (res.code == 200) {
            this.code = res.code;
            // res.data.payInfo.totalPay = "61.5";
            this.parentRefData = res.data.payInfo;
            this.refundInfo = res.data.refundInfo;
            this.refdata.refundMoeny = Number(res.data.payInfo.totalPay);
            this.refdata.shouPay = 0;
            // 退款模态框
            if (refOrder) {
              this.message = res.data;
              this.open = true;
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          // console.log(err);
        });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      list(this.queryParams)
        .then((response) => {
          if (response.data.orderInfos.length == 1) {
            this.list = response.data.orderInfos;
            this.total = response.data.totalPage;
            this.loading = false;
            // 跳转到详情页面
            this.$router.push({
              path: `orderMessage`,
              query: {
                orderCode: response.data.orderInfos[0].orderCode,
              },
            });
            return;
          }
          this.list = response.data.orderInfos;
          this.total = response.data.totalPage;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    /** 查询分销商列表 */
    getDicts() {
      querytrader().then((response) => {
        response.data.forEach((e) => {
          e.traderName = e.trader;
        });
        response.data.unshift({ trader: "all", traderName: "全部" });
        this.statusOptions = response.data;
      });
    },
    // findDicts(val) {
    //   var txt;
    //   this.statusOptions.forEach((e) => {
    //     if (e.trader == val) {
    //       txt = e.traderName;
    //     }
    //   });
    //   return txt;
    // },
    // 登录状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 订单号历史记录
    getSearchList() {
      try {
        if (localStorage.getItem("searchList")) {
          this.arr = JSON.parse(localStorage.getItem("searchList"));
        }
      } catch (err) {}
      this.arr.unshift({
        value: this.queryParams.keyword,
        address: this.queryParams.keyword,
      });
      this.arr = utils.utils.arrUnique(this.arr);
      this.arr.splice(10, this.arr.length - 9);
      localStorage.setItem("searchList", JSON.stringify(this.arr));
    },
    handleSelect(item) {
      console.log(item);
    },
    querySearch(queryString, cb) {
      try {
        var restaurants = this.arr;
        var results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      } catch (err) {}
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 订单号历史记录========================结束
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
      this.getSearchList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      // this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.infoId);
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const infoIds = row.infoId || this.ids;
      this.$confirm(
        '是否确认删除访问编号为"' + infoIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delLogininfor(infoIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 清空按钮操作 */
    handleClean() {
      this.$confirm("是否确认清空所有登录日志数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return cleanLogininfor();
        })
        .then(() => {
          this.getList();
          this.msgSuccess("清空成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/logininfor/export",
        {
          ...this.queryParams,
        },
        `logininfor_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.refItem {
  line-height: 50px;
}
#refDiv {
  font-size: 15px;
}
</style>